package dawn.jxufe.community.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author dawn21
 * @version 1.0
 * @date 2022/7/10 10:26
 * @component 邮箱客户端，委托新浪发送邮箱。
 */
@Component
public class MailClient {
    // 日志
    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);
    //依赖注入,邮件发送器
    @Resource
    private JavaMailSender mailSender;
    //发送人
    @Value("${spring.mail.username}")
    private String from;
    //接收人，标题，内容
    public void sendMail(String to, String subject, String content){
        //构建邮件,帮助类辅助构建
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);//设置发件人
            helper.setTo(to);//设置收件人
            helper.setSubject(subject);//设置标题
            helper.setText(content,true);//设置内容,是html文本。
            mailSender.send(helper.getMimeMessage());//发送
        } catch (MessagingException e) {
            logger.error("发送邮件失败;" + e.getMessage());
        }
        //发送邮件
    }
}
